package com.example.jpetstoreback.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.FileNotFoundException;
import java.sql.SQLIntegrityConstraintViolationException;

/*
 *全局异常处理
 */
@ControllerAdvice(annotations = {Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 插入employee数据库值唯一
     * @param ex
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public CommonResponse<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());
        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split("'");
            String msg = split[1] + "已存在！";
            return CommonResponse.createForError(msg);
        }
        return CommonResponse.createForError("未知错误！");
    }
}
